﻿using Castle.DynamicProxy;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Framework.LinkTrackingLog.AI_Deepseek
{
    /// <summary>
    /// 服务集合扩展方法
    /// 用于自动注册监控相关服务
    /// 
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加自动方法监控
        /// </summary>
        public static IServiceCollection AddAutoMonitoring(this IServiceCollection services)
        {
            //// 在Program.cs或Startup.cs中的配置
            //
            //// 注册Controller并添加Action过滤器
            //builder.Services.AddControllers(options =>
            //{
            //    options.Filters.Add<ApiExecutionTimeFilter>(); // 添加API监控过滤器
            //});
            //
            //// 添加自动方法监控
            //builder.Services.AddAutoMonitoring();

            // 注册监控核心服务
            services.AddSingleton<IMethodMonitoringService, MethodMonitoringService>();

            // 注册拦截器和代理生成器
            services.AddSingleton<MethodExecutionInterceptor>();
            services.AddSingleton<ProxyGenerator>();

            // 扫描程序集中所有接口(排除监控服务本身)
            var serviceTypes = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(a => a.GetTypes())
                .Where(t => t.IsInterface && t != typeof(IMethodMonitoringService))
                .ToList();

            // 为每个服务接口注册代理装饰器
            foreach (var serviceType in serviceTypes)
            {
                var implementationType = services.FirstOrDefault(s => s.ServiceType == serviceType)?.ImplementationType;
                if (implementationType != null)
                {
                    services.DecorateWithMonitoring(serviceType, implementationType);
                }
            }

            return services;
        }

        /// <summary>
        /// 为指定服务类型添加监控代理装饰器
        /// </summary>
        private static void DecorateWithMonitoring(this IServiceCollection services, Type serviceType, Type implementationType)
        {
            services.Decorate(serviceType, (target, provider) =>
            {
                // 获取代理生成器和拦截器
                var generator = provider.GetRequiredService<ProxyGenerator>();
                var interceptor = provider.GetRequiredService<MethodExecutionInterceptor>();

                // 创建代理对象
                return generator.CreateInterfaceProxyWithTarget(serviceType, target, interceptor);
            });
        }
    }
}
